package com.polito.mad.bikeponyapp.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.persistence.DeliveriesRepository;
import com.polito.mad.bikeponyapp.persistence.DeliveryItem;
import com.polito.mad.bikeponyapp.persistence.RepositoryHolder;
import com.polito.mad.bikeponyapp.service.ServerCommunicationService.ProximityIntentReceiver;
import com.polito.mad.bikeponyapp.util.AsyncTaskForResultMessage;
import com.polito.mad.bikeponyapp.util.DialogCreator;
import com.polito.mad.bikeponyapp.util.ResultMessage;

public class PickupActivity extends Activity {

	
	private static final String DELIVERY_ID_PARAM_NAME = "deliveryId";
	private static final String ITEM_ID_PARAM_NAME = "itemId";
	private long itemId = -1;
	private long deliveryId = -1;//delivery id is used for savedinstancestate which is used to persist the dialog state
	
	DeliveriesRepository deliveryRepo;
	public static final int TAKE_PICTURE_ACTION_CODE = 1111;
	
	Boolean isShowingDataSavedDialog = false;

	private Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_pickup);
		
		context = this;
		setFinishOnTouchOutside (false);
		
		deliveryRepo = ((RepositoryHolder)getApplication()).getDeliveriesRepository();
		if(savedInstanceState!=null && savedInstanceState.containsKey(ITEM_ID_PARAM_NAME))
		{
			itemId = savedInstanceState.getLong(ITEM_ID_PARAM_NAME);
			deliveryId = savedInstanceState.getLong(DELIVERY_ID_PARAM_NAME );
			isShowingDataSavedDialog = savedInstanceState.getBoolean("isShowingDataSavedDialog" );
			
		}else
		{
			Bundle myBundle = this.getIntent().getExtras();
			if(myBundle != null && myBundle.containsKey(getString(R.string.delivery_id_notification_intent_param)))
			{
				itemId = myBundle.getLong(getString(R.string.delivery_id_notification_intent_param));
			}
		}
		
		if(isShowingDataSavedDialog)
		{
			showProgress(true);
			showDataSavedDialog(deliveryId);
		}
		
		final DeliveryItem deliveryItemPickup = deliveryRepo.get(itemId);
		if(deliveryItemPickup != null)
		{
			deliveryId = deliveryItemPickup.getDeliveryId();
		}
		
		
		Button cancelBtn = (Button) findViewById(R.id.pickup_activity_cancel_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		Button okBtn = (Button) findViewById(R.id.pickup_activity_ok_btn);
		okBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				EditText eT = (EditText) findViewById(R.id.pickup_activity_edit_text) ;
				
				if(eT.getText().toString().isEmpty())
				{
					Toast toast = Toast.makeText(PickupActivity.this, getString(R.string.pickup_track_code_not_entered), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL, 0, 0);
					toast.show();
					return;
				}
				
				
				verifyCode(deliveryItemPickup);
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		EditText edText = (EditText) findViewById(R.id.pickup_activity_edit_text);
		boolean bFocus = edText.requestFocus();
		
		if(bFocus)
		{
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
            
			//InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    //mgr.showSoftInput(edText, 0);
		    			
		}
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		EditText edText = (EditText) findViewById(R.id.pickup_activity_edit_text);
		boolean bFocus = edText.requestFocus();
		
		if(bFocus)
		{
			InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    mgr.hideSoftInputFromWindow(edText.getWindowToken(), 0);
		}
		
	}
	
	private boolean verifyCode(final DeliveryItem deliveryItemPickup)
	{
		boolean result = false;
		
		StringBuilder b = new StringBuilder();
		b.append(getString(R.string.server_com_protocol))
		.append("://")
		.append(getString(R.string.server_host))
		.append(":")
		.append(getString(R.string.server_port))
		.append(getString(R.string.server_services_context_path))
		.append(getString(R.string.server_services_agent_path))
		.append(getString(R.string.server_services_agent_verify_pickup));
		
		AsyncTaskForResultMessage asyncTask = new AsyncTaskForResultMessage(b.toString(), true, new AsyncTaskForResultMessage.OnTaskCompletionListener() {
			
			@Override
			public void onTaskEnded(ResultMessage resultMessage) {
				
				if(resultMessage.getStatusCode() == ResultMessage.STATUS_OK)
				{//code verified form the server
					
					try {
						deliveryRepo.delete(deliveryItemPickup);
						
						SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(PickupActivity.this);
						Editor editor = pref.edit();
						editor.putBoolean(getString(R.string.delivery_status_updated), true);
						editor.commit();
						
						isShowingDataSavedDialog = true;
						
						showDataSavedDialog(deliveryId);

						NotificationManager mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
						mNM.cancel(ProximityIntentReceiver.DELIVERY_POINT_NOTIFICATION_ID);
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				else
				{
					showProgress(false);
					
					Toast toast = Toast.makeText(PickupActivity.this, resultMessage.getMessage(), Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL, 0, 0);
					toast.show();
				}
			}
		});
		
		ContentValues cv = new ContentValues();
		String agentId = PreferenceManager.getDefaultSharedPreferences(this).getString(getText(R.string.userid_pref).toString(), "");
		cv.put("agentId", agentId);
		cv.put(DELIVERY_ID_PARAM_NAME,deliveryId);
		
		EditText eT = (EditText) findViewById(R.id.pickup_activity_edit_text) ;
		cv.put("trackingCode", eT.getText().toString());
				
		asyncTask.execute(cv);
		
		showProgress(true);
		//Intent intent = new Intent(this, ProgressActivity.class);
		//startActivity(intent);
		
		return result;
	}
	
	private void showDataSavedDialog(long deliveryId)
	{
		showControls(false);
		String sMessage = getString(R.string.pickup_data_saved_correctly) + Long.toString(deliveryId) ;
		
		//String sDeliveryId = "Delivery Identity:" + Long.toString(deliveryId);
		
		AlertDialog dialog = DialogCreator.createAlertDialog(PickupActivity.this, sMessage, getString(R.string.pickup_alert_dialog_title));
		
		dialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.ok),new Dialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				closePickupActivity();
			}
		});
			
		dialog.show();
		
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.pickup, menu);
		return false;
	}
	
	private void showProgress(boolean bShow)
	{
		showControls(!bShow);//to show the progress all of the other controls should be removed and vice-versa
		
		ProgressBar pBar = (ProgressBar) findViewById(R.id.pickup_activity_progress_bar) ;
		pBar.setVisibility(bShow?View.VISIBLE:View.GONE);
		
	}
	
	private void showControls(boolean bShow)
	{
		//if show progress then hide all buttons and show progress widget
		int myViewState = bShow?View.VISIBLE:View.GONE;
		
		//TextView titleTV = (TextView) findViewById(R.id.pickup_activity_title);
		//titleTV.setVisibility(myViewState);
		
		
		Button cancelBtn = (Button) findViewById(R.id.pickup_activity_cancel_btn);
		cancelBtn.setVisibility(myViewState);
		
		Button okBtn = (Button) findViewById(R.id.pickup_activity_ok_btn);
		okBtn.setVisibility(myViewState);
		
		EditText eT = (EditText) findViewById(R.id.pickup_activity_edit_text) ;
		eT.setVisibility(myViewState);
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(bShow)
		{		
			imm.showSoftInput(eT, 0);
		}
		else
		{
			imm.hideSoftInputFromWindow(eT.getWindowToken(), 0);
		}
		
		ProgressBar pBar = (ProgressBar) findViewById(R.id.pickup_activity_progress_bar) ;
		pBar.setVisibility(myViewState);
		
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putLong(ITEM_ID_PARAM_NAME, itemId);
		outState.putLong(DELIVERY_ID_PARAM_NAME, deliveryId);
		outState.putBoolean("isShowingDataSavedDialog", isShowingDataSavedDialog);
		
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		closePickupActivity();			
	}
	
	private void closePickupActivity() {
		PreferenceManager.getDefaultSharedPreferences(PickupActivity.this).edit()
			.putBoolean(getString(R.string.notification_set_icon), false)
			.commit();
		setResult(RESULT_OK);
		finish();
	}
}
